Ext.onReady(function () {
	var dayAxis = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
	var colors = new Array('#33CC33','#2044ba','#f0a50a','#810065');
	var normalColors = new Array('#C8C8C8','#969696','#646464');
	var anomalyColors = new Array('#C80000','#960000','#640000');
	
	var weekLabels = new Array({
		xtype: 'label',
		text: 'Week 1'
	},{
		xtype: 'label',
		text: 'Week 2'
	},{
		xtype: 'label',
		text: 'Week 3'
	},{
		xtype: 'label',
		text: 'Week 4'
	},{
		xtype: 'label',
		text: 'Week 5'
	},{
		xtype: 'label',
		text: 'Week 6'
	});
	
	Ext.define("handle", {
		extend: "Ext.data.Model",
		fields: [{ 
			name: "id", 
			type: "string" 
		},{ 
			name: "name", 
			type: "string" 
		}]
	});
	
	var dayLabels = new Array({
		xtype: 'label',
		text: 'Sunday',
		margin: '0 0 0 10'
	},{
		xtype: 'label',
		text: 'Monday',
		margin: '0 0 0 10'
	},{
		xtype: 'label',
		text: 'Tuesday',
		margin: '0 0 0 10'
	},{
		xtype: 'label',
		text: 'Wednesday',
		margin: '0 0 0 10'
	},{
		xtype: 'label',
		text: 'Thursday',
		margin: '0 0 0 10'
	},{
		xtype: 'label',
		text: 'Friday',
		margin: '0 0 0 10'
	},{
		xtype: 'label',
		text: 'Saturday',
		margin: '0 0 0 10'
	});
	
	var hourLabels = new Array({
		xtype: 'label',
		text: '0000',
		margin: '0 0 0 10'
	},{
		xtype: 'label',
		text: '0100',
		margin: '0 0 0 10'
	},{
		xtype: 'label',
		text: '0200',
		margin: '0 0 0 10'
	},{
		xtype: 'label',
		text: '0300',
		margin: '0 0 0 10'
	},{
		xtype: 'label',
		text: '0400',
		margin: '0 0 0 10'
	},{
		xtype: 'label',
		text: '0500',
		margin: '0 0 0 10'
	},{
		xtype: 'label',
		text: '0600',
		margin: '0 0 0 10'
	},{
		xtype: 'label',
		text: '0700',
		margin: '0 0 0 10'
	},{
		xtype: 'label',
		text: '0800',
		margin: '0 0 0 10'
	},{
		xtype: 'label',
		text: '0900',
		margin: '0 0 0 10'
	},{
		xtype: 'label',
		text: '1000',
		margin: '0 0 0 10'
	},{
		xtype: 'label',
		text: '1100',
		margin: '0 0 0 10'
	},{
		xtype: 'label',
		text: '1200',
		margin: '0 0 0 10'
	},{
		xtype: 'label',
		text: '1300',
		margin: '0 0 0 10'
	},{
		xtype: 'label',
		text: '1400',
		margin: '0 0 0 10'
	},{
		xtype: 'label',
		text: '1500',
		margin: '0 0 0 10'
	},{
		xtype: 'label',
		text: '1600',
		margin: '0 0 0 10'
	},{
		xtype: 'label',
		text: '1700',
		margin: '0 0 0 10'
	},{
		xtype: 'label',
		text: '1800',
		margin: '0 0 0 10'
	},{
		xtype: 'label',
		text: '1900',
		margin: '0 0 0 10'
	},{
		xtype: 'label',
		text: '2000',
		margin: '0 0 0 10'
	},{
		xtype: 'label',
		text: '2100',
		margin: '0 0 0 10'
	},{
		xtype: 'label',
		text: '2200',
		margin: '0 0 0 10'
	},{
		xtype: 'label',
		text: '2300',
		margin: '0 0 0 10'
	});

	var handles = Ext.create('Ext.data.Store', {
		model: 'handle',
		proxy: {
			type: 'ajax',
			url: 'http://ec2-54-221-173-96.compute-1.amazonaws.com:5000/twitter/api/alpha/get_handles',
			reader: {
				type:'json',
				root: 'records'
			}
		},
		autoLoad: true
	});

	var panel = Ext.create('widget.panel', {
		title: 'Twitter Life Patterns',
		region:'center',
		renderTo: Ext.getBody(),
		autoScroll: true,
		style: {
			background: '#C8C8C8'
		},
		width: 1680,
		height: 1000,
		tbar: [{
			xtype: 'datefield',
			name: 'start',
			ref: 'start',
			fieldLabel: 'Start Date',
			allowBlank: false,
			blankText: 'This field is required',
			emptyText: 'Pick Start Date',
			maxValue: new Date(),
			listeners: {
				select: function(picker, date, eopts){
					picker.ownerCt.items.items[1].setMinValue(date);
					picker.ownerCt.items.items[1].setMaxValue(Ext.Date.add(date, Ext.Date.DAY, 30));
				}
			}
		},{
			xtype: 'datefield',
			name: 'end',
			ref: 'end',
			fieldLabel: 'End Date',
			allowBlank: false,
			blankText: 'This field is required',
			emptyText: 'Pick End Date',
			maxValue: new Date(),
			listeners: {
				select: function(picker, date, eopts){
					picker.ownerCt.items.items[0].setMinValue(Ext.Date.add(date, Ext.Date.DAY, -30));
					picker.ownerCt.items.items[0].setMaxValue(date);
				}
			}
		},{
			xtype: 'combo',
			name: 'id',
			editable: true,
			queryMode: 'local',
			displayField: 'name',
			valueField: 'name',
			allowBlank: false,
			blankText: 'This field is required',
			emptyText: 'Select Twitter Handle',
			fieldLabel: 'Twitter Handle',
			typeAhead: true,
			store: handles
		},{
			xtype: 'button', 
			text: 'Submit',
			handler: function() {
				var tbar = panel.getDockedItems('toolbar[dock="top"]')[0].items.items;

				if(!tbar[0].validate()){
					Ext.Msg.alert('Error', 'Please input a start date.');
				} 
				else if(!tbar[1].validate()){
					Ext.Msg.alert('Error', 'Please input an end date.');
				}
				else if(!tbar[2].validate()){
					Ext.Msg.alert('Error', 'Please input a twitter handle.');
				}
				else{
					var method = 'days';
					if(Ext.Date.getElapsed(tbar[0].getValue(),tbar[1].getValue()) > (1000 * 60 * 60 * 24 * 8)){
						method = 'weeks';
					}

					panel.loadData(tbar[0].getValue(),tbar[1].getValue(),tbar[2].getValue(),method);
				}
			}
		},{
			xtype: 'button', 
			text: 'Reset',
			handler: function() {
				var tbar = panel.getDockedItems('toolbar[dock="top"]')[0].items.items;

				tbar[0].setValue('');
				panel.resetMinMaxDate(tbar[0]);
				tbar[1].setValue('');
				panel.resetMinMaxDate(tbar[1]);
				tbar[2].clearValue();
				panel.removeAll();
				
			}
		}],
		resetMinMaxDate: function(date){
			date.setMinValue(null);
			date.setMaxValue(new Date());
		},
		loadData: function(start,end,id,method){
			
			var items = new Array();
			var yAxis = start.getDay();
			
			Ext.Ajax.request({
				url: 'http://ec2-54-221-173-96.compute-1.amazonaws.com:5000/twitter/api/alpha/get_datetimes',
				params: {
					handle: id,
					start:Date.parse(start),
					end:Date.parse(end) + 82700000,
					method:method
				},
				method: 'GET',
				success: function(response) {
					var values = Ext.decode(response.responseText);
					
					var json = values.records;
					var xlabels = hourLabels;
					var ylabels = dayLabels;
					var mod = 24;
					var width = 60;
					var height = 52;
					var maxAdj = 18;
					
					
					if(method == 'weeks'){
						xlabels = dayLabels;
						ylabels = weekLabels;
						mod = 7;
						width = 120;
						height = 100;
						maxAdj = 40;
						yAxis = 0;
					}

					var blankRow = {
				        xtype: 'label',
						text: '',
						padding: 20,
						colspan: mod + 1
				    };

					var blankCell = {
						xtype: 'label',
						text: '',
					};
					
					var table = Ext.create('Ext.Panel', {
				        id: 'tableCharts',
				        layout: {
				            type: 'table',
				            columns: mod + 1
				        },
				        defaults: {
				        	width:width+10,
				        	height: height+10
				        },
						items:[],
						toggleField: function(field){
							Ext.each(this.items.items,function(item){
								if(item.xtype == 'chart'){
									item.toggleValue(field);
									item.redraw();
								}
							});
						},
					});
					
					table.add(blankCell);
					for(var i = 0; i < xlabels.length; i++){
						table.add(xlabels[i]);
					}
					
					var index = 0;
					for(var i = 0; i < json.length; i++){
						var container = Ext.create('Ext.container.Container', {
						    width: '100%',
						    border: 1,
						    style: {
						    	borderColor:'grey',
						    	borderStyle:'solid', 
						    	borderWidth:'.5px'
						    }				   
						});
						
						
						if(index % mod == 0){
							table.add(ylabels[yAxis]);
							yAxis++;
						}
						if(index == 0 && method == 'weeks'){
							for(var j = 0; j < start.getDay(); j++){
								table.add(Ext.create('Ext.container.Container', {
								    width: '100%',
								    border: 1,
								    style: {
								    	borderColor:'grey',
								    	borderStyle:'solid', 
								    	borderWidth:'.5px'
								    },	
									items: [blankCell]
								}));
								index++;
							}
						}
						var pie = json[i].data;

						var total = pie.tweet + pie.tweet_with_url + pie.retweet + pie.retweet_with_url;
						
						var store = Ext.create('Ext.data.JsonStore', {
							fields: ['name', 'data'],
							data: [{
								'name': 'Tweet',
								'data': pie.tweet
							},{
								'name': 'Tweet with Url',
								'data': pie.tweet_with_url
							},{
								'name': 'Retweet',
								'data': pie.retweet
							},{
								'name': 'Retweet with Url',
								'data': pie.retweet_with_url
							}]
						});
						
						
						var adjustment = 0;

						if(total > 0 && total < values.maximum){
							
							adjustment = (1 - (total /values.maximum)) * maxAdj;
						}

						var colorShadow = pie.anomaly ? anomalyColors:normalColors;
						var chart = Ext.create('Ext.chart.Chart', {
							xtype: 'chart',
							id: 'chart-' + i,
							animate: true,
							width: width - adjustment,
							height: height - adjustment,
							store: store,
							date: json[i].time,
							handle: id,
							method: method,
							shadow: true,
							theme: 'Base:gradients',
							series: [{
								type: 'pie',
								field: 'data',
								style: {
							    	cursor:'pointer'
								},
								shadowAttributes:[{
								    "stroke-width": 6,
								    "stroke-opacity": 1,
								    stroke: colorShadow[0],
								    translate: {
								        x: 1.2,
								        y: 2
								    }
								},
								{
								    "stroke-width": 4,
								    "stroke-opacity": 1,
								    stroke: colorShadow[1],
								    translate: {
								        x: 0.9,
								        y: 1.5
								    }
								},
								{
								    "stroke-width": 2,
								    "stroke-opacity": 1,
								    stroke: colorShadow[2],
								    translate: {
								        x: 0.6,
								        y: 1
								    }
								}],
								scope: this,
								tips: {
									trackMouse: true,
									width: 250,
									height: 30,
									renderer: function(storeItem, item) {	    
										var total = 0;
										storeItem.store.each(function(rec) {
											total += rec.get('data');
										});

										if(total != 0){
											this.setTitle(storeItem.get('name') + ': ' + Math.round(storeItem.get('data') / total * 100) + '% out of Total ' + total);
										}
										else{
											this.setTitle('No data for this item');
										}
									}
										}
									}],
									toggleValue: function(field){
										var pie = this.series.items[0];
										console.log(this.series);
										pie.__excludes[field] = !pie.isExcluded(field);
									},
									listeners : {
										click: function(e){

											var popup =  Ext.create('StatsWindow', {
												twitterHandle:this.handle,
												twitterDate:this.date,
												twitterMethod:this.method
											});
											
											popup.show();
										}
									}
						});

						chart.themeAttrs.colors = colors;
						table.add((Ext.create('Ext.container.Container', {
						    width: '100%',
						    border: 1,
						    style: {
						    	borderColor:'grey',
						    	borderStyle:'solid', 
						    	borderWidth:'.5px'
						    },	
							items: [chart]
						})));
						index++;
					}

					for(var i = 0; i < 4; i++){
						table.add(blankRow);
					}
					
					table.add({
						xtype: 'label',
						text: 'Legend',
						style: 'font-size:18px'
					});
					
					for(var i = 0; i < 4; i++){
						table.add(blankRow);
					}
					
					table.add({
						xtype: 'label',
						text: 'Tweet'
					});
					table.add({
						xtype: 'draw',
						tableRef: table,
						viewBox: false,
						width: 66,
						height: 54,
						style: {
					    	cursor:'pointer'
						},
						items: [{
							type: 'rect',
							width: 25,
							height: 25,
							radius: 5,
							y: 20,
							fill: colors[0],
							listeners: {
								click: {
									fn: function(el){
										el.surface.tableRef.toggleField(0);
									}
								}
							}}]
					});
					table.add({
						xtype: 'label',
						text: 'Tweet with URL'
					});
					table.add({
						xtype: 'draw',
						viewBox: false,
						tableRef: table,
						width: 66,
						height: 54,
						style: {
					    	cursor:'pointer'
						},
						items: [{
							type: 'rect',
							width: 25,
							height: 25,
							radius: 5,
							y: 20,
							fill: colors[1],
							listeners: {
								click: {
									fn: function(el){ 
										el.surface.tableRef.toggleField(1);
									}
								}
							}}]
					});
					table.add({
						xtype: 'label',
						text: 'Retweet'
					});
					table.add({
						xtype: 'draw',
						viewBox: false,
						tableRef: table,
						width: 66,
						height: 54,
						style: {
					    	cursor:'pointer'
						},
						items: [{
							type: 'rect',
							width: 25,
							height: 25,
							radius: 5,
							y: 20,
							fill: colors[2],
							listeners: {
								click: {
									fn: function(el){ 
										el.surface.tableRef.toggleField(2);
									}
								}
							}}]
					});
					table.add({
						xtype: 'label',
						text: 'Retweet with URL'
					});
					table.add({
						xtype: 'draw',
						viewBox: false,
						tableRef: table,
						width: 66,
						height: 54,
						style: {
					    	cursor:'pointer'
						},
						items: [{
							type: 'rect',
							width: 25,
							height: 25,
							radius: 5,
							y: 20,
							fill: colors[3],
							listeners: {
								click: {
									fn: function(el){ 
										el.surface.tableRef.toggleField(3);
									}
								}
							}}]
					});
				
					panel.removeAll();
					panel.add(table);
				} 
			});	
		}
	});
});
